<?php 
	include ('lib/twitese.php');
	$title = "Sign In";
	include ('inc/header.php');
	
	/* Start session and load lib */
	if(!isset($_SESSION)){
		session_start();
	}
	require_once ('lib/twitese.php');
	require_once ('lib/authorize.php');
?>

<div id="login_area">
	<div id="error">

<?php
	if ( isset($_POST['username']) && isset($_POST['password']) ) {
		if (is_authorized_user($_POST['username']) == FALSE)
		{
			echo '<p>Login failed. User not allowed.</p>';
		}
		else
		{
			/* Create TwitterOAuth object and get request token */
			$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
	
			/* Get request token */
			$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
	
			/* Save request token to session */
			$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
			$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
	
			/* If last connection fails don't display authorization link */
			switch ($connection->http_code) {
				case 200:
					/* Build authorize URL */
					$authorise_url = $connection->getAuthorizeURL($token);
					$str = file_get_contents($authorise_url);
					$authenticity_pattern = '/.*input name="authenticity_token" type="hidden" value="([a-z0-9]*)".*/';
					preg_match($authenticity_pattern,$str,$matches);
					$postdata = "authenticity_token=".$matches[1];
					$oauth_token_pattern = '/input id="oauth_token" name="oauth_token" type="hidden" value="([A-Za-z0-9]*)".*/';
					preg_match($oauth_token_pattern,$str,$matches);
					$postdata .= "&oauth_token=".$matches[1];
					$postdata .= "&session[username_or_email]=".$_POST['username']."&session[password]=".$_POST['password']."&submit=Allow";
					$url = "http://twitter.com/oauth/authorize";
					$ch = curl_init($url);
					curl_setopt($ch,CURLOPT_POST,TRUE);
					curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
					curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
					$str = curl_exec($ch);
					curl_close($ch);
					$redirect_url_pattern = '/<a href="([^"]*)">click here<\/a>/';
					preg_match($redirect_url_pattern,$str,$matches);
					if (!empty($matches[1])) {
						$url = str_replace("&amp;","&",$matches[1]);
						header("Location: ".$url);
						exit();
					} else {
						echo "<p>Login failed. Please check your username and password.</p>";	
					} 
					//end of try to oauth
					break;
				default:
					echo 'Could not connect to Twitter. Refresh the page or try again later.';
					break;
			}
		}
	} else {
		echo "<p>Illegal request. Please go back.</p>";
	}
?>

	</div>
</div>	

<?php 
	include ('inc/footer.php');
?>
